//
//  MyTicket.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/21/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "MyTicket.h"

@implementation MyTicket

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)dealloc {
    [_tblView release];
    [_lbButton release];
    [_btnButton release];
    [_btnMyticket release];
    [super dealloc];
}
- (void)setupMyticket{
    
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    
    _btnButton.exclusiveTouch = YES;
    _btnButton.hidden = YES;
    _btnMyticket.exclusiveTouch = YES;
    _btnMyticket.hidden = YES;
    _lbButton.text = [_fromView isEqualToString:@"CategoryView"] ? @"CATEGORY" : @"FIND EVENT";
    
    
   }
- (void)setupUI{
    
    _btnButton.hidden = NO;
    _btnMyticket.hidden = NO;
    ////////////////////////////////////////////////////////////////////////////
    //Setup tableView
    if (!_tblView) {
        _tblView = [[UITableView alloc] initWithFrame:CGRectMake(5, 140, 309, [Utilities isDeviceFourInches] ? self.bounds.size.height -  200 : self.bounds.size.height -  230)];
        _tblView.backgroundColor = [UIColor clearColor];
        _tblView.delegate = self;
        _tblView.dataSource = self;
        [self addSubview:_tblView];
    }
    else{
        [_tblView reloadData];
    }
    
    ////////////////////////////////////////////////////////////////////////////
    //Pull to refresh
    if (refeshHeaderTableView == nil) {
        refeshHeaderTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tblView.bounds.size.height, self.frame.size.width, _tblView.bounds.size.height)];
        refeshHeaderTableView.delegate = self;
        [_tblView addSubview:refeshHeaderTableView];
        [refeshHeaderTableView setWhiteTextColor];
    }
    else{
        [self doneLoadingTableViewData];
    }

}




////////////////////////////////////////////////////////////////////////
#pragma mark - btnMyTicketView_ChangeFindEvent_CLicked
- (IBAction)btnMyTicketView_ChangeFindEvent_CLicked:(id)sender{
    if ([_fromView isEqualToString:@"CategoryView"]) {
        if ([_myTicKetDelegate respondsToSelector:@selector(myTicKetButtonCategoryClick:)]) {
            [_myTicKetDelegate myTicKetButtonCategoryClick:self];
        }
    }
    else{
        if ([_myTicKetDelegate respondsToSelector:@selector(myTicKetButtonFindEventClick:)]) {
            [_myTicKetDelegate myTicKetButtonFindEventClick:self];
        }
    }
}


////////////////////////////////////////////////////////////////////////
//Get data from server
- (void)getMyTicKetFromServer{
//    dispatch_async(kBgQueue, ^{

//        NSString *urlString = [NSString stringWithFormat:@"%@%@%@%@%@", URL_island_API, user_event_API, TOKEN__island, TOKEN_ACCESS , [[NSUserDefaults standardUserDefaults] objectForKey:access_token_eTicket_userDefault]];
//        NSURL *url = [NSURL URLWithString:urlString];
//        requestServer = [ASIFormDataRequest requestWithURL:url];
//        [requestServer setTimeOutSeconds:20];
//        [requestServer setCompletionBlock:^{
//            
//            NSError *error = nil;
//            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
//            
//            /////////////////////////////////////////////////////////////////////
//            //Set error server
//            if (error) {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
//                [alert show];
//                SAFE_RELEASE_OBJECT(alert);
//                return;
//            }
//
//            /////////////////////////////////////////////////////////////////////
//            //Set error json
//            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
//            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
//                NSArray *messageArray = [jsonError objectForKey:@"message"];
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
//                [alert show];
//                SAFE_RELEASE_OBJECT(alert);
//                return;
//            }

            
            ////////////////////////////////////////////////////////////////////////
            SAFE_RELEASE_ARRAY(_arrayData);
            _arrayData = [[NSMutableArray alloc] init];
            for (NSInteger i = 0; i < 5; i++) {
                EventTicket *event = [[EventTicket alloc] init];
                event.titleEvent = @"Title test";
                event.startTimeEvent = @"21/04/2013 15:40 PM";
                [_arrayData addObject:event];
                SAFE_RELEASE_OBJECT(event);
            }
            //Load tableView
            [self setupUI];
            
            //OFf hud
            mLoading = NO;
            
//            
//        }];
//        [requestServer setFailedBlock:^{
//            
//        }];
//        [requestServer startSynchronous];
//    
//    });
}


////////////////////////////////////////////////////////////////////////
#pragma mark - UITableView Delegate * Datasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_arrayData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MyTicketCell";
    MyTicketCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTicketCell" owner:self options:nil];
        for (id cur in nib) {
            if ([cur isKindOfClass:[MyTicketCell class]]) {
                cell = (MyTicketCell *)cur;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    
    EventTicket *event = [_arrayData objectAtIndex:indexPath.row];
    cell.lbTitle.text = event.titleEvent;
    cell.lbStartTime.text = event.startTimeEvent;
    return cell;
}



////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[refeshHeaderTableView egoRefreshScrollViewDidScroll:scrollView];
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[refeshHeaderTableView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark EGORefreshTableHeader Delegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
	
    // send request to server
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(refreshTime)
                                               object:nil];
    
    addingDuration = 0;
    [self getMyTicKetFromServer];
}
-(void)refreshTime{
    addingDuration ++;
    
    [self performSelector:@selector(refreshTime) withObject:nil afterDelay:60.0];
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	NSLog(@"Data Source Last Updated");
	return [NSDate date];
	
}
- (void)reloadTableViewDataSource{
	NSLog(@"ReloadTable view source");
	_reloading = YES;
	
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
	
}
- (void)doneLoadingTableViewData{
	//  model should call this when its done loading
    NSLog(@"Done Loading Table View Data");
	_reloading = NO;
	[refeshHeaderTableView egoRefreshScrollViewDataSourceDidFinishedLoading:_tblView];
	
}





////////////////////////////////////////////////////////////////////////
#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
    }
}


@end
